<script lang="ts" setup>
import type { Repository } from './types';

import { onBeforeMount, ref } from 'vue';

import { useAccess } from '@croco/framework/access';
import { VIcon } from '@croco/framework/icons';
import { Page } from '@croco/framework/libraries';
import { $t } from '@croco/framework/locales';

import { ElButton } from 'element-plus';

import { service } from '#/api/request';
import { DataTable } from '#/components/data-table';

import BrowseFile from './browse.vue';
import { defaultFileDatabaseId, useTable } from './data';
import EditFileDatabase from './database.vue';
import EditFileRepository from './repository.vue';

defineOptions({ name: 'SystemFile' });

const { hasPermission } = useAccess();

const pageRef = ref();
const dataTableRef = ref<Array<InstanceType<typeof DataTable>>>(); // 由于tab-pane是动态循环，所以会有多个
const browseFileRef = ref<InstanceType<typeof BrowseFile>>();
const editFileDatabaseRef = ref<InstanceType<typeof EditFileDatabase>>();
const editFileRepositoryRef = ref<InstanceType<typeof EditFileRepository>>();

const editRepositoryPermission = hasPermission('system:file:repository:edit');

const active = ref('1');
const loading = ref(false);
const repositories = ref<Repository[]>([]);
const columns = useTable(({ code, scope }) => {
    switch (code) {
        case 'browse': {
            browseFileRef.value?.open(scope.row);
            break;
        }
        case 'edit': {
            onEditFileDatabase(scope.row);
            break;
        }
        case 'remove': {
            onDeleteFileDatabase(scope.row);
            break;
        }
        default: {
            break;
        }
    }
});

function initRepositoryTab() {
    loading.value = true;
    service
        .get('/system/file/repository')
        .then(({ data }) => {
            if (data) {
                if (repositories.value.length > 0) {
                    repositories.value[0] = data;
                } else {
                    repositories.value.push(data);
                }
                active.value = data.id;
                defaultFileDatabaseId.value = data.defaultFileDatabaseId;
            }
        })
        .catch((error) => {
            pageRef.value?.setApiState(error);
        })
        .finally(() => (loading.value = false));
}

function onEditFileRepository(row = repositories.value[0]) {
    editFileRepositoryRef.value?.open({
        data: row,
        success: initRepositoryTab,
    });
}

function onEditFileDatabase(row?: any) {
    editFileDatabaseRef.value?.open({
        data: row,
        success: dataTableRef.value?.[0]?.refresh,
    });
}

function onDeleteFileDatabase(row: any) {
    service.confirm({
        message: `确定删除文件库【${row.name}】,包括所有目录及其文件且无法恢复?`,
        url: '/system/file/database',
        data: { id: row.id },
        success: () => dataTableRef.value?.[0]?.refresh(),
    });
}

onBeforeMount(() => initRepositoryTab());
</script>
<template>
    <Page ref="pageRef" auto-content-height>
        <el-tabs v-model="active" type="border-card" class="kt-tabs" addable v-loading="loading">
            <template #add-icon>
                <ElButton v-auth="'system:file:repository:edit'" link @click="onEditFileRepository()" />
            </template>
            <el-tab-pane v-for="repository in repositories" :key="repository.id" :label="repository.name" :name="repository.id" style="height: 100%">
                <DataTable ref="dataTableRef" :columns="columns" api="/system/file/database">
                    <template #extra>
                        <ElButton v-auth="'system:file:database:add'" @click="onEditFileDatabase()" />
                    </template>
                </DataTable>
            </el-tab-pane>

            <el-empty v-if="repositories.length === 0" class="h-full">
                <template v-if="typeof editRepositoryPermission === 'object'" #description>
                    <span>点击右上角&nbsp;&nbsp;</span>
                    <el-icon>
                        <VIcon :icon="editRepositoryPermission.icon" />
                    </el-icon>
                    <span>&nbsp;初始化文件仓信息（注：文件仓仅且只有一个）</span>
                </template>
                <template v-else #description>
                    {{ $t('ui.fallback.http.forbidden') }}
                </template>
            </el-empty>
        </el-tabs>

        <EditFileRepository ref="editFileRepositoryRef" />
        <EditFileDatabase ref="editFileDatabaseRef" />
        <BrowseFile ref="browseFileRef" />
    </Page>
</template>
<style lang="scss" scoped>
.kt-tabs {
    :deep(.el-tabs__header) {
        height: 39px;
        .el-tabs__new-tab {
            height: 100%;
            width: 39px;
            border: unset;
            margin: 0;

            button {
                padding: 0;
                height: 100%;
                width: 100%;
                border-radius: unset;
            }
        }
    }
}

.file-system {
    height: 100%;
    padding: 5px;

    .el-tabs__new-tab {
        border: unset;
        width: unset;
    }

    .item {
        margin-top: 5px;
    }

    .el-badge__content.is-fixed {
        right: -5px;
        top: 5px;
    }

    .el-tabs--top {
        height: 100%;
    }

    :deep(.el-tabs__header) {
        margin-bottom: 0;
    }
}
</style>
